<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/ficon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/icon.png">
  <link rel="mask-icon" href="/images/icon.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bqlin.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":true,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":{"gitalk":{"order":-2}},"activeClass":"gitalk"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false},"motion":{"enable":false,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="媒体创作和编辑基本是AVFoundation的高级接口，较少涉及底层接口。整个过程总的来说就是构建AVAsset的过程，而在视频编辑中，构建的是AVMutableComposition的过程。 整体关系">
<meta property="og:type" content="article">
<meta property="og:title" content="AVFoundation影片编辑API">
<meta property="og:url" content="https://bqlin.github.io/posts/avfoundation_movie_edit_api/index.html">
<meta property="og:site_name" content="權咚领域">
<meta property="og:description" content="媒体创作和编辑基本是AVFoundation的高级接口，较少涉及底层接口。整个过程总的来说就是构建AVAsset的过程，而在视频编辑中，构建的是AVMutableComposition的过程。 整体关系">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-11-08T02:11:40.000Z">
<meta property="article:modified_time" content="2021-11-08T02:11:40.000Z">
<meta property="article:author" content="權咚">
<meta property="article:tag" content="Apple">
<meta property="article:tag" content="音视频">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://bqlin.github.io/posts/avfoundation_movie_edit_api/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>AVFoundation影片编辑API | 權咚领域</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-105338942-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-105338942-1');
      }
    </script>


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?98fcf61fd269408d07dcbc1e49311f9a";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="權咚领域" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">權咚领域</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Making app a work of art.</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bqlin.github.io/posts/avfoundation_movie_edit_api/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/icon.png">
      <meta itemprop="name" content="權咚">
      <meta itemprop="description" content="🤘🤯👾">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="權咚领域">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          AVFoundation影片编辑API
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-11-08 10:11:40" itemprop="dateCreated datePublished" datetime="2021-11-08T10:11:40+08:00">2021-11-08</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/AVFoundation/" itemprop="url" rel="index"><span itemprop="name">AVFoundation</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>6.6k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>6 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>媒体创作和编辑基本是AVFoundation的高级接口，较少涉及底层接口。整个过程总的来说就是构建AVAsset的过程，而在视频编辑中，构建的是AVMutableComposition的过程。</p>
<h2 id="整体关系">整体关系</h2>
<p><strong>Composition</strong>：作为内容主体，一个抽象的可编辑的AVAsset子类，提供面向对象的多轨操作。</p>
<ul>
<li>CompositionTrack ×N：管理时间，总的音视频轨信息。
<ul>
<li>AssetTrack片段 ×N</li>
<li>轨道的偏好信息：<code>naturalTimeScale</code>、<code>preferredTransform</code>、<code>preferredVolume</code></li>
</ul></li>
</ul>
<p><strong>AudioMix</strong>：附加信息，对音量的描述</p>
<ul>
<li><code>inputParameters</code>：AudioMixInputParameters ×N：描述音量（+时间=渐变）、变速时的音调策略</li>
</ul>
<p>AudioMixInputParameters的<code>audioTapProcessor</code>可以使用AudioUnit给音频增加效果，但似乎查不到具体的额API文档，可参考：<a target="_blank" rel="noopener" href="https://developer.apple.com/forums/thread/90879">MTAudioProcessingTap with kMTAudio… | Apple Developer Forums</a>、<a target="_blank" rel="noopener" href="https://github.com/gchilds/MTAudioProcessingTap-in-Swift">gchilds/MTAudioProcessingTap-in-Swift: Example of creating an MTAudioProcessingTap in Swift4.2</a>。</p>
<p><strong>VideoComposition</strong>：附加信息，对画面的描述</p>
<ul>
<li><p>视频属性控制：</p>
<ul>
<li>frameDuration</li>
<li>renderSize</li>
<li>colorParimaties</li>
<li>colorTransferFunction</li>
<li>colorYCbCrMatrix</li>
</ul></li>
<li><p>视频操作，通过以下三种方式：</p>
<ul>
<li><p><code>instructions</code>：AVVideoCompositionInstructionProtocol ×N</p>
<ul>
<li><p>VideoCompositionLayerInstruction：提供几种图像以时间点、时间区间/渐变操作</p>
<ul>
<li><p>opacity</p></li>
<li><p>transform</p></li>
<li><p>cropRectangle</p></li>
</ul></li>
</ul></li>
<li><p><code>animationTool</code>：提供与Core Animation的几种交互方式，不能实时预览的，即设置到playerItem看不到效果。</p>
<ul>
<li>新增一个用CALayer表示的视频轨：<code>init(additionalLayer: CALayer, asTrackID: CMPersistentTrackID)</code></li>
<li>用CALayer层级关系管理视频轨：<code>init(postProcessingAsVideoLayer: CALayer, in: CALayer)</code>、<code>init(postProcessingAsVideoLayers: [CALayer], in: CALayer)</code></li>
</ul></li>
<li><p><code>customVideoCompositorClass</code>：自己实现一个VideoComposition，可通过GL、Metal实现自定义的转场</p></li>
</ul></li>
</ul>
<p>以上API的Mutable版本的类才是可编辑的。</p>
<p>以上的Composition，可用于创建PlayerItem、AssetExportSession。AudioMix、VideoComposition作为属性设置到AssetExportSession、AssetReaderAudioMixOutput、playerItem。</p>
<h2 id="具体api">具体API</h2>
<h3 id="avmutablecomposition">AVMutableComposition</h3>
<p>AVAsset的子类，因此这是最后预览、导出操作的数据对象。</p>
<h4 id="整体操作">整体操作</h4>
<p>对整个composition对象进行整体操作，当然这会涉及多个轨道，除了对整体进行时间伸缩，否则较少使用。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">/// 插入空占位</span><br><span class="line">func insertEmptyTimeRange(_ timeRange: CMTimeRange)</span><br><span class="line"></span><br><span class="line">/// 插入asset</span><br><span class="line">func insertTimeRange(_ timeRange: CMTimeRange, of asset: AVAsset, at startTime: CMTime) throws</span><br><span class="line"></span><br><span class="line">/// 移除时间段的内容，注意这里不会移除既有的轨道。</span><br><span class="line">func removeTimeRange(_ timeRange: CMTimeRange)</span><br><span class="line"></span><br><span class="line">/// 伸缩时间，即改变时间区间内所有轨道的时长</span><br><span class="line">func scaleTimeRange(_ timeRange: CMTimeRange, toDuration duration: CMTime)</span><br><span class="line"></span><br><span class="line">/// 配置视频画幅尺寸</span><br><span class="line">var naturalSize: CGSize &#123; get set &#125;</span><br></pre></td></tr></table></figure>
<h4 id="轨道操作">轨道操作</h4>
<p>大多数操作都是基于轨道。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">/// 添加、移除轨道</span><br><span class="line">func addMutableTrack(withMediaType mediaType: AVMediaType, preferredTrackID: CMPersistentTrackID) -&gt; AVMutableCompositionTrack?</span><br><span class="line">func removeTrack(_ track: AVCompositionTrack)</span><br><span class="line"></span><br><span class="line">// 其他API只是获取轨道等非常用操作</span><br></pre></td></tr></table></figure>
<h3 id="avmutablecompositiontrack">AVMutableCompositionTrack</h3>
<p>一个可修改的轨道。</p>
<h4 id="常用配置属性">常用配置属性</h4>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">/// 视频翻转矩阵</span><br><span class="line">var preferredTransform: CGAffineTransform &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 音频轨道音量</span><br><span class="line">var preferredVolume: Float &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 其他不太常用的属性</span><br><span class="line">var languageCode: String? &#123; get set &#125;</span><br><span class="line">var extendedLanguageTag: String? &#123; get set &#125;</span><br><span class="line">var naturalTimeScale: CMTimeScale &#123; get set &#125;</span><br></pre></td></tr></table></figure>
<p>增删改查</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">func insertEmptyTimeRange(_ timeRange: CMTimeRange)</span><br><span class="line">func insertTimeRange(_ timeRange: CMTimeRange, of track: AVAssetTrack, at startTime: CMTime) throws</span><br><span class="line">func insertTimeRanges(_ timeRanges: [NSValue], of tracks: [AVAssetTrack], at startTime: CMTime) throws // 似乎不常用</span><br><span class="line">func removeTimeRange(_ timeRange: CMTimeRange)</span><br><span class="line">func scaleTimeRange(_ timeRange: CMTimeRange, toDuration duration: CMTime)</span><br><span class="line">var segments: [AVCompositionTrackSegment]! &#123; get set &#125;</span><br></pre></td></tr></table></figure>
<h3 id="avmutableaudiomix">AVMutableAudioMix</h3>
<p>包含混音（目前的混音只有音量调节）参数，所以其对象只有一个属性：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var inputParameters: [AVAudioMixInputParameters] &#123; get set &#125;</span><br></pre></td></tr></table></figure>
<h4 id="avmutableaudiomixinputparameters">AVMutableAudioMixInputParameters</h4>
<p>音频混音参数。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">/// 创建</span><br><span class="line">convenience init(track: AVAssetTrack?)</span><br><span class="line">/// 创建后也可以修改trackId更变应用的轨道</span><br><span class="line">var trackID: CMPersistentTrackID &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 设置音量</span><br><span class="line">func setVolume(_ volume: Float, at time: CMTime)</span><br><span class="line">func setVolumeRamp(fromStartVolume startVolume: Float, toEndVolume endVolume: Float, timeRange: CMTimeRange)</span><br><span class="line"></span><br><span class="line">/// 设置音调算法</span><br><span class="line">var audioTimePitchAlgorithm: AVAudioTimePitchAlgorithm? &#123; get set &#125;</span><br></pre></td></tr></table></figure>
<h3 id="avmutablevideocomposition">AVMutableVideoComposition</h3>
<p>控制视频轨道组合行为。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">/// 创建</span><br><span class="line">init(propertiesOf asset: AVAsset)</span><br><span class="line"></span><br><span class="line">/// 配置视频相关属性</span><br><span class="line">var frameDuration: CMTime &#123; get set &#125;</span><br><span class="line">var renderSize: CGSize &#123; get set &#125;</span><br><span class="line">var renderScale: Float &#123; get set &#125; // 不常用</span><br><span class="line">var colorPrimaries: String? &#123; get set &#125;</span><br><span class="line">var colorTransferFunction: String? &#123; get set &#125;</span><br><span class="line">var colorYCbCrMatrix: String? &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 配置视频操作</span><br><span class="line">var instructions: [AVVideoCompositionInstructionProtocol] &#123; get set &#125;</span><br><span class="line">var animationTool: AVVideoCompositionCoreAnimationTool? &#123; get set &#125;</span><br><span class="line">var customVideoCompositorClass: AVVideoCompositing.Type? &#123; get set &#125;</span><br></pre></td></tr></table></figure>
<h3 id="avmutablevideocompositioninstruction">AVMutableVideoCompositionInstruction</h3>
<p>提供一个时间范围内的视频组织信息。由一组AVMutableVideoCompositionLayerInstruction对象格式定义的指令组成的。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">/// 自顶而下排列的layerInstructions</span><br><span class="line">var layerInstructions: [AVVideoCompositionLayerInstruction] &#123; get set &#125;</span><br><span class="line">var timeRange: CMTimeRange &#123; get set &#125;</span><br><span class="line">var enablePostProcessing: Bool &#123; get set &#125;</span><br><span class="line">var backgroundColor: CGColor? &#123; get set &#125;</span><br></pre></td></tr></table></figure>
<h3 id="avmutablevideocompositionlayerinstruction">AVMutableVideoCompositionLayerInstruction</h3>
<p>给视频特效，用于定义给定视频轨道应用的基于时间的模糊、变形、和裁剪效果。从其构建方式可见，其更类似于AVMutableAudioMixInputParameters。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">/// 构建</span><br><span class="line">convenience init(assetTrack track: AVAssetTrack)</span><br><span class="line">var trackID: CMPersistentTrackID &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 支持的操作</span><br><span class="line">func setOpacity(_ opacity: Float, at time: CMTime)</span><br><span class="line">func setOpacityRamp(fromStartOpacity startOpacity: Float, toEndOpacity endOpacity: Float, timeRange: CMTimeRange)</span><br><span class="line">func setTransform(_ transform: CGAffineTransform, at time: CMTime)</span><br><span class="line">func setTransformRamp(fromStart startTransform: CGAffineTransform, toEnd endTransform: CGAffineTransform, timeRange: CMTimeRange)</span><br><span class="line">func setCropRectangle(_ cropRectangle: CGRect, at time: CMTime)</span><br><span class="line">func setCropRectangleRamp(fromStartCropRectangle startCropRectangle: CGRect, toEndCropRectangle endCropRectangle: CGRect, timeRange: CMTimeRange)</span><br></pre></td></tr></table></figure>
<p>LayerInstruction是应用于一个轨道的，意味着要想在应用特效的时候能看到底下的视频，则需要多个视频轨道。</p>
<h3 id="videocompositioncoreanimation">VideoComposition+CoreAnimation</h3>
<p>视频编辑中除了可以叠加轨道，还可以叠加CALayer。这通过VideoComposition的animationTool实现。其类是AVVideoCompositionCoreAnimationTool：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">/// 添加额外的图层</span><br><span class="line">convenience init(additionalLayer layer: CALayer, asTrackID trackID: CMPersistentTrackID)</span><br><span class="line"></span><br><span class="line">/// 自定义组织视频层与根图层。这里animationLayer是根图层，videoLayer视频层是其子图层，除此以外还可以在animationLayer添加更多子图层。</span><br><span class="line">convenience init(postProcessingAsVideoLayer videoLayer: CALayer, in animationLayer: CALayer)</span><br><span class="line"></span><br><span class="line">/// 拷贝视频帧到多个视频层</span><br><span class="line">convenience init(postProcessingAsVideoLayers videoLayers: [CALayer], in animationLayer: CALayer)</span><br></pre></td></tr></table></figure>
<p>在视频中使用CoreAnimation，常需要设置geometryFlipped属性，让其坐标翻转一遍。</p>
<p>通过AVVideoCompositionCoreAnimationTool使用Core Animation时需要注意：</p>
<ul>
<li>用<code>AVCoreAnimationBeginTimeAtZero</code>表示0时间点；</li>
<li><code>isRemovedOnCompletion</code>设为false；</li>
<li>避免使用与UIView关联的CALayer。</li>
</ul>
<h3 id="avassetexportsession">AVAssetExportSession</h3>
<p>高级导出类，是个高级API，要想更细化地配置，还是需要AVAssetReader+AVAssetWriter。</p>
<h4 id="构建">构建</h4>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">init?(asset: AVAsset, presetName: String)</span><br></pre></td></tr></table></figure>
<p>当然可以直接构建后就开始导出。其音视频的转码配置都囊括在presetName中，即既有的方案中去直接套用。</p>
<h4 id="配置">配置</h4>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">/// 输出文件路径</span><br><span class="line">var outputURL: URL? &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 文件类型，准确地来说是容器类型</span><br><span class="line">var outputFileType: AVFileType? &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 文件长度限制</span><br><span class="line">var fileLengthLimit: Int64 &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 导出时间区间</span><br><span class="line">var timeRange: CMTimeRange &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 附带的元数据</span><br><span class="line">var metadata: [AVMetadataItem]? &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 混音</span><br><span class="line">var audioMix: AVAudioMix? &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 音调算法（在伸缩时长时）</span><br><span class="line">var audioTimePitchAlgorithm: AVAudioTimePitchAlgorithm &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// 是否为网络播放优化</span><br><span class="line">var shouldOptimizeForNetworkUse: Bool &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// video composition</span><br><span class="line"> var videoComposition: AVVideoComposition? &#123; get set &#125;</span><br><span class="line"></span><br><span class="line">/// custom video compositor</span><br><span class="line">var customVideoCompositor: AVVideoCompositing? &#123; get &#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Apple/" rel="tag"># Apple</a>
              <a href="/tags/%E9%9F%B3%E8%A7%86%E9%A2%91/" rel="tag"># 音视频</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/x264_encoder_parameter_setting/" rel="prev" title="x264编码器参数设置">
      <i class="fa fa-chevron-left"></i> x264编码器参数设置
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/avfoundation_export_api/" rel="next" title="AVFoundation导出API">
      AVFoundation导出API <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%95%B4%E4%BD%93%E5%85%B3%E7%B3%BB"><span class="nav-text">整体关系</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B7%E4%BD%93api"><span class="nav-text">具体API</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#avmutablecomposition"><span class="nav-text">AVMutableComposition</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%95%B4%E4%BD%93%E6%93%8D%E4%BD%9C"><span class="nav-text">整体操作</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BD%A8%E9%81%93%E6%93%8D%E4%BD%9C"><span class="nav-text">轨道操作</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#avmutablecompositiontrack"><span class="nav-text">AVMutableCompositionTrack</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%B8%B8%E7%94%A8%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7"><span class="nav-text">常用配置属性</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#avmutableaudiomix"><span class="nav-text">AVMutableAudioMix</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#avmutableaudiomixinputparameters"><span class="nav-text">AVMutableAudioMixInputParameters</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#avmutablevideocomposition"><span class="nav-text">AVMutableVideoComposition</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#avmutablevideocompositioninstruction"><span class="nav-text">AVMutableVideoCompositionInstruction</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#avmutablevideocompositionlayerinstruction"><span class="nav-text">AVMutableVideoCompositionLayerInstruction</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#videocompositioncoreanimation"><span class="nav-text">VideoComposition+CoreAnimation</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#avassetexportsession"><span class="nav-text">AVAssetExportSession</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%9E%84%E5%BB%BA"><span class="nav-text">构建</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%85%8D%E7%BD%AE"><span class="nav-text">配置</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="權咚"
      src="/images/icon.png">
  <p class="site-author-name" itemprop="name">權咚</p>
  <div class="site-description" itemprop="description">🤘🤯👾</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">84</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/bqlin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;bqlin" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/hearingdog" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;hearingdog" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/metal-reference-translation" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;metal-reference-translation" rel="noopener" target="_blank">Metal内参</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/wwdc21" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;wwdc21" rel="noopener" target="_blank">WWDC21 内参</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2016 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">權咚</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">279k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">4:14</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'default',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '7ed324dbfd2741c35c0e',
      clientSecret: '75a59e1f6a55202c4a1b0ec3570ad5b5dccbc390',
      repo        : 'bqlin.github.io',
      owner       : 'bqlin',
      admin       : ['bqlin'],
      id          : 'de670f79a35c8eaa42bef8f7a5910ca6',
        language: 'zh-CN',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","vOffset":-100},"mobile":{"show":false,"scale":0.5},"log":false});</script></body>
</html>
